package web.synchorichned;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author ZhangGJ
 * @Date 2022/02/07 13:57
 */
@Slf4j
public class SynchronizedController8 {

    @GetMapping("process7")
    public String process(String orderId) {
        SynchronizedKey2 synchronizedKey = new SynchronizedKey2();
        synchronizedKey.exec(orderId, () -> {
            log.info("=======Start: {}", orderId);
            service(orderId);
            log.info("=======End: {}", orderId);
        });
        return "Success!";
    }

    public void service(String orderId) {
        try {
            Thread.sleep(3000L);
            log.info("=====================执行了: {}", orderId);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < 20000; i++) {
//            threadList.add(new Thread(new SynchronizedController7()));
        }
        threadList.parallelStream().forEach(Thread::start);
//        threadList.stream().forEach(Thread::start);
    }

}


class SynchronizedKey2 {
    Map<String, ReentrantLock> mutexCache = new ConcurrentHashMap<>();
    ReentrantLock mutex4Key = null;
    ReentrantLock mutexInCache;
    public void exec(String key, Runnable statement) {
        do {
            if (mutex4Key != null) {
                mutex4Key.unlock();;
            }
            mutex4Key = mutexCache.computeIfAbsent(key, k -> new ReentrantLock());
            mutex4Key.lock();
            mutexInCache = mutexCache.get(key);
        } while (mutexCache == null || mutex4Key != mutexInCache);
        try {
            statement.run();
        } finally {
            if (mutex4Key.getQueueLength() == 0) {
                this.mutexCache.remove(key);
            }
            mutex4Key.unlock();
        }
    }
}
